package com.imooc.project.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.toolkit.CollectionUtils;
import com.baomidou.mybatisplus.core.toolkit.Wrappers;
import com.imooc.project.entity.Resource;
import com.imooc.project.dao.ResourceMapper;
import com.imooc.project.service.IResourceService;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.imooc.project.vo.ResourceVO;
import org.springframework.stereotype.Service;

import java.util.List;

/**
 * <p>
 * 资源表 服务实现类
 * </p>
 *
 * @author yin.liu8
 * @since 2021-08-20
 */
@Service
public class ResourceServiceImpl extends ServiceImpl<ResourceMapper, Resource> implements IResourceService {

    @Override
    public List<ResourceVO> listResourceByRoleId(Long roleId) {
        //条件构造器
        QueryWrapper<Resource> query = Wrappers.<Resource>query();
        //查询第一级目录
        query.eq("rr.role_id", roleId).isNull("re.parent_id");
        //一级目录的查询结果
        List<ResourceVO> resourceVOS = baseMapper.listResource(query);
        //下面的循环查询二级目录
        resourceVOS.forEach(r -> {
            Long resourceId = r.getResourceId();
            //再创建条件构造器
            QueryWrapper<Resource> subWrapper = Wrappers.<Resource>query();
            subWrapper.eq("rr.role_id", roleId)
                    .eq("re.parent_id", resourceId);
            List<ResourceVO> subResourceVOS = baseMapper.listResource(subWrapper);
            if (CollectionUtils.isNotEmpty(subResourceVOS)) {
                r.setSubs(subResourceVOS);
            }
        });

        return resourceVOS;
    }
}
